package william.binarysearch;

/**
 * @author ZhangShenao
 * @date 2024/1/18
 * @description <a href="https://leetcode.cn/problems/binary-search/description/">...</a>
 */
public class Leetcode704_二分查找 {
    public int search(int[] nums, int target) {
        //边界条件校验
        if (nums == null || nums.length == 0) {
            return -1;
        }

        //在数组的[L,R]范围内进行二分查找
        int L = 0;
        int R = nums.length - 1;

        while (L <= R) { //需要考虑区间内仅剩一个元素的情况
            //取终点
            int mid = L + ((R - L) >> 1);

            //将中间位置的元素与目标元素进行比较,通过大小移动边界
            if (nums[mid] == target) {
                return mid;
            }

            if (nums[mid] > target) {
                R = mid - 1;
            } else {
                L = mid + 1;
            }
        }

        //循环退出,未找到目标元素
        return -1;
    }
}
